package cacheMachine

import (
	"errors"
	"fmt"
	"strconv"

	"wowCoupon.com/cache"
	"wowCoupon.com/models"
	"wowCoupon.com/pkg/tools"
)

var CacheMachiner CacheMachine = CacheMachine{}

type CacheMachine struct {
}

func (c *CacheMachine) Businesses() ([]string, error) {
	//business不会太多，所以直接使用Keys方法一次性返回所有的business key即可
	keys, err := cache.Rdb.Keys("*wowCoupon*")
	return keys, err
}

func (c *CacheMachine) PreLoadTemplate(
	id int64, GoodId int64, Type int64, Title string, Comments string,
	ValidStartTime int64, ValidEndTime int64, Status int64) (string, error) {

	fields := map[string]interface{}{
		"good_id":          GoodId,
		"type":             Type,
		"title":            Title,
		"comments":         Comments,
		"valid_start_time": ValidStartTime,
		"valid_end_time":   ValidEndTime,
		"status":           Status,
	}

	fmt.Println("id: ", id)
	return cache.RdbTP.HMSet(strconv.Itoa(int(id)), fields)

}

//Preload seckill info to Redis
func (c *CacheMachine) PreLoadStockToRedis(couponMeta *models.CouponMeta) (bool, error) {
	BusinessKey := tools.GenRedisKeyBusiness(couponMeta.BusinessId)
	StockKey := tools.GenRedisHashKeyStock(couponMeta.GoodId, int64(couponMeta.ID))
	return cache.Rdb.HSet(BusinessKey, StockKey, couponMeta.RemainAmount)
}

func (c *CacheMachine) PreLoadIssueStartTimeToRedis(couponMeta *models.CouponMeta) (bool, error) {
	BusinessKey := tools.GenRedisKeyBusiness(couponMeta.BusinessId)
	IssueStartTimeKey := tools.GenRedisHashKeyIssueStartTime(couponMeta.GoodId, int64(couponMeta.ID))
	return cache.Rdb.HSet(BusinessKey, IssueStartTimeKey, couponMeta.IssueStartTime)
}

func (c *CacheMachine) PreLoadIssueEndTimeToRedis(couponMeta *models.CouponMeta) (bool, error) {
	BusinessKey := tools.GenRedisKeyBusiness(couponMeta.BusinessId)
	IssueEndTimeKey := tools.GenRedisHashKeyIssueEndTime(couponMeta.GoodId, int64(couponMeta.ID))
	return cache.Rdb.HSet(BusinessKey, IssueEndTimeKey, couponMeta.IssueEndTime)
}

func (c *CacheMachine) PreLoadRobberListToRedis(couponMeta *models.CouponMeta) (bool, error) {
	RobberListKey := tools.GenRedisKeyUserIdList(couponMeta.BusinessId, couponMeta.GoodId, int64(couponMeta.ID))
	return cache.Rdb.BfReserve(RobberListKey, 0.01, couponMeta.Amount)
}

func (c *CacheMachine) ScanBusinessExpirationWith(business string, fn func(hashKvSlice []string) error) error {
	if fn == nil {
		return errors.New("callback function fn should not be nil")
	}

	var (
		hashKvSlice []string
		cursor      uint64 = 0
		err         error
		count       int64 = 1000
	)

	for {
		hashKvSlice, cursor, err = cache.Rdb.HScan(business, cursor, "*ie", count)

		if err != nil {
			return err
		}

		//call the customized function
		if err = fn(hashKvSlice); err != nil {
			return err
		}

		if cursor == 0 {
			return nil
		}
	}
}
